package com.tornado.system.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tornado.system.model.Goods;
import com.tornado.system.model.Shopping;
import com.tornado.system.model.User;
import com.tornado.system.service.IGoodsService;
import com.tornado.system.service.IshoppingService;
/**
 * 购物车控制器
 * @author FengYun_rumple
 * @date 2017年8月8日下午8:31:52
 */
@Controller
@RequestMapping("/shopping")
public class shoppingController {
	@Autowired
	private IshoppingService shoppingService;
	@Autowired
	private IGoodsService goodsService;
	/**
	 * 返回shopping表中的所有数据,并通过商品id查询所有的商品信息；
	 */
	@RequestMapping(value="show",method=RequestMethod.GET)
	public String getShoppingList(Model model){
		//返回购物车表中的所有数据
		List<Shopping> shopps = shoppingService.getShoppinglist();
		//new一个空的商品list，用来存储商品对象
		List<Goods> goods = new ArrayList();
		for(Shopping shopp : shopps){
			goods.add(goodsService.load(shopp.getGoodsId()));
		}
		model.addAttribute("shopping",shopps);
		model.addAttribute("goods", goods);
		return "/shopping/shopping";
	}
	/**
	 * 商品首页跳转到购物车页面：
	 * 		1.如果用户未登录（session为空），不允许跳转到购物车页面，提示用户请先登陆
	 * 		2.登陆状态下，点击“添加到购物车”：Ⅰ：该用户之前没有添加该商品，直接插入到shopping表
	 * 								     Ⅱ：该用户之前添加过该商品，在数据库中的count字段的值，增加1
	 */
	@RequestMapping(value="buytoshopping",method=RequestMethod.POST)
	public String buyToshopping(HttpSession session,@RequestParam Integer goodsId){
		//通过商品id拿到商品对象
		Goods good = goodsService.load(goodsId);
		//判断用户是否登陆
		if(session !=null){
			User user = (User)session.getAttribute("user");
			int id = user.getUserId();
			//通过userId和商品id返回一个购物车对象
			Shopping sop = shoppingService.selectByug(id, good.getId());
			/**
			 * 判断该用户之前有没有添加过该商品：
			 * 				添加过：sop!=null→count+1
			 * 			      没添加过：sop==null→插入数据到购物车表中
			 */
			if(sop == null){
				Shopping shopping = new Shopping(id,good.getId(),1);
				shoppingService.insertRecord(shopping);
			}else{
				//将购物车中这个人的商品数量加1
				int count=sop.getCount()+1;
				shoppingService.updateSopCount(count,id);
			}
			return "/shopping/shopping";
		}else{
			return "login.jsp";//未登录情况下，直接跳转到登陆页面
		}
	}
	@RequestMapping(value="delete",method=RequestMethod.GET)
	public String deleteShopping(Model model,Integer id){
		//返回购物车表中的所有数据
		shoppingService.deleterecord(id);
		return "redirect:/shopping/show";
	}
}
